package com.example.automotive.handler;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import com.example.automotive.MainActivity;
import com.example.automotive.R;
import com.example.automotive.util.DataManager;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gson.Gson;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutionException;
import com.example.automotive.util.ONNXManager;

public class CameraHandler {

    private static final String TAG = "CameraHandler"; // 定义日志标签
    private final MainActivity mainActivity; // 定义 MainActivity 实例
    private ImageCapture imageCapture; // 定义 ImageCapture 实例
    private DataManager dataManager;
    private ONNXManager onnxManager;
    private boolean isCapturingImage = false;

    public CameraHandler(MainActivity mainActivity) { // CameraHandler 构造函数
        this.mainActivity = mainActivity; // 初始化 MainActivity 实例
        this.dataManager = new DataManager(TAG, mainActivity); // 初始化数据管理器
        this.onnxManager = new ONNXManager(mainActivity); // 初始化模型管理器
        requestCameraPermission(); // 请求摄像头权限

        // 请求存储权限
        if (ContextCompat.checkSelfPermission(mainActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
        }

        startCamera(); // 启动摄像头
    }

    // 请求摄像头权限
    private void requestCameraPermission() {
        // 检查摄像头权限是否被授予
        if (ContextCompat.checkSelfPermission(mainActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 如果没有授予权限，请求摄像头权限
            ActivityCompat.requestPermissions(mainActivity, new String[]{Manifest.permission.CAMERA}, 2);
        }
    }


    // 启动摄像头
    public void startCamera() {
        // 获取 ProcessCameraProvider 的实例
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(mainActivity);
        // 添加监听器，当摄像头提供者准备就绪时调用
        cameraProviderFuture.addListener(() -> {
            try {
                // 获取 ProcessCameraProvider 实例
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                // 绑定摄像头预览
                bindPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
                // 处理绑定失败的情况
                Log.e(TAG, "Binding failed", e);
            }
        }, ContextCompat.getMainExecutor(mainActivity));
    }

    // 绑定摄像头预览
    private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        // 获取 PreviewView 实例
        PreviewView previewView = mainActivity.findViewById(R.id.previewView);
        // 创建 Preview 实例
        Preview preview = new Preview.Builder().build();
        // 创建 CameraSelector 实例，指定使用后置摄像头
        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();
        // 创建 ImageCapture 实例
        imageCapture = new ImageCapture.Builder().build();

        // 添加图像分析器用于实时推断
        // 添加图像分析器用于实时推断
        ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                .build();
        imageAnalysis.setAnalyzer(ContextCompat.getMainExecutor(mainActivity), new ImageAnalysis.Analyzer() {
            @Override
            public void analyze(@NonNull ImageProxy image) {
                if (!isCapturingImage) {
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);

                    // 将字节数组转换为Bitmap对象
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                    // 调用ONNXManager进行推断
                    onnxManager.runModel(bitmap);

                    image.close();
                }
            }
        });

        // 设置预览的 SurfaceProvider
        preview.setSurfaceProvider(previewView.getSurfaceProvider());

        // 解绑所有用例，然后绑定预览和图片捕捉用例到摄像头
        cameraProvider.unbindAll();
        cameraProvider.bindToLifecycle((LifecycleOwner) mainActivity, cameraSelector, preview, imageCapture);
    }

    // 拍照功能
    public void takePhoto() {
        // 如果 imageCapture 为空，则返回
        if (imageCapture == null) return;

        isCapturingImage = true;
        // 调用 takePicture 方法捕捉照片
        imageCapture.takePicture(ContextCompat.getMainExecutor(mainActivity), new ImageCapture.OnImageCapturedCallback() {

            @Override
            public void onCaptureSuccess(@NonNull ImageProxy image) {
                // 获取图像数据
                ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);

                long timestamp = System.currentTimeMillis(); // 获取当前时间戳

                // 将图像数据存入本地
                String filePath = dataManager.saveImageToLocal(bytes, timestamp);
                System.out.println(filePath);
                if (filePath!=null){
                    String sensorDataJson = new Gson().toJson(mainActivity.sensorData);
                    dataManager.uploadDataToServer(filePath, sensorDataJson);
                }
                // 将图像数据编码为 Base64 字符串
                String encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);

                // 将ImageProxy转换为Bitmap
                Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

                // 推断
                onnxManager.runModel(bitmap);
//                List<float[]> validDetections = DetectionUtils.filterAndParseDetections(detections, 0.5f);  // 设置置信度阈值为 0.5
//                DetectionUtils.drawDetectionsOnBitmap(bitmap, validDetections);

//                runOnUiThread(() -> imageView.setImageBitmap(bitmap));
                Log.d(TAG, "Encoded image size: " + encodedImage.length());
                // 关闭图像资源
                image.close();
                isCapturingImage = false;
            }

            @Override
            public void onError(@NonNull ImageCaptureException exception) {
                // 处理捕捉照片失败的情况
                Log.e(TAG, "Photo capture failed: " + exception.getMessage(), exception);
            }
        });
    }

    // 请求权限结果的回调处理
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // 检查请求码和权限结果
        if (requestCode == 2 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 如果权限被授予，则启动摄像头
            startCamera();
        }
    }





}
